package org.zero.monitor;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Objects;

import org.zero.entity.Request;
import org.zero.entity.User;
import org.zero.util.Connection;
import org.zero.view.RegisterWindow;

public class RegisterMonitor implements ActionListener {
	private RegisterWindow registerWindow;

	public RegisterMonitor(RegisterWindow registerWindow) {
		this.registerWindow = registerWindow;
	}

	public void actionPerformed(ActionEvent actionEvent) {
		String actionCommand = actionEvent.getActionCommand();
		String name = registerWindow.getName();
		String nickname = registerWindow.getNickname();
		String password = registerWindow.getPassword();
		String confirmPassword = registerWindow.getConfirmPassword();

		if ("Register".equals(actionCommand)) {

			if (name.isBlank() || nickname.isBlank() || password.isBlank() || confirmPassword.isBlank()) {
				registerWindow.setMessage("请输入相关信息！！！");
				return;
			}

			if (name.length() > 15 || nickname.length() > 15) {
				registerWindow.setMessage("用户名或昵称过长（大于15位）");
				registerWindow.setName("");
				registerWindow.setNickname("");
				return;
			}

			if (password.length() < 6 || password.length() > 12) {
				registerWindow.setMessage("密码的长度为6-12");
				registerWindow.setPassword("");
				registerWindow.setConfirmPassword("");
				return;
			}

			// 判断密码是否一致
			if (!Objects.equals(password, confirmPassword)) {
				registerWindow.setMessage("密码不一致，请重新输入");
				registerWindow.setPassword("");
				registerWindow.setConfirmPassword("");
				return;
			}

			// 封装 User 对象
			User user = new User();
//			user.setId(id);
			user.setName(name);
			user.setNickname(nickname);
			user.setPassword(password);

			// 封装 Request 对象
			Request request = new Request();
			request.setRequestServiceName("Register");
			request.setFromUser(user);

			Connection.send(request);
			Connection.receive(registerWindow);
		}

		if ("Reset".equals(actionCommand)) {
			registerWindow.setMessage("");
			registerWindow.setName("");
			registerWindow.setNickname("");
			registerWindow.setPassword("");
			registerWindow.setConfirmPassword("");
		}
	}

}
